<?php


namespace app\helper;


use app\model\AdminKanjiaHelp;
use app\model\AdminKanjiaOrder;
use app\model\AdminKanjiaRule;
use app\model\AppWxUser;
use Exception;
use think\Db;

class KanJiaHelper
{
    /**
     * 砍价
     * @param $kanJiaOrderId int 砍价订单id
     * @param $uid String 帮助的用户uid
     * @return array
     */
    public function kanJia($kanJiaOrderId,$uid)
    {

        $kanjiaModel = AdminKanjiaOrder::get($kanJiaOrderId,null,true);
        if(!$kanjiaModel){
            return ['done' => false];
        }
        $originalPrice= $kanjiaModel->original_price;
        $lowestPrice = $kanjiaModel->lowest_price;
        $currentPrice = $kanjiaModel->current_price;
        $ruleId = $kanjiaModel->rule_id;
        $kanJiaHelp  = AdminKanjiaHelp::get(['uid'=>$uid,'tid'=>$kanjiaModel->tid,'kanjia_order_id'=>$kanJiaOrderId]);
//        if($kanJiaHelp){
//            return ['done' => false,'msg'=>'您已经帮忙砍过了'];
//        }
        $randPrice = null;
        $ruleModel = AdminKanjiaRule::get($ruleId, null, true);
        if ($ruleModel) {
            $rule = json_decode($ruleModel->rule,true);
            for ($i = 0; $i < count($rule); $i++) {
                if ($currentPrice >= $rule[$i]['price']) {
                    $randPrice = mt_rand($rule[$i]['start_price'], $rule[$i]['end_price']);
                    break;
                }
            }
        }
        if($randPrice==null){
            //这里应该还要搞一个默认规则,以原价和最低价的差价的5%~15%之间进行随机减
            $b = $originalPrice - $lowestPrice;
            $randPrice = mt_rand($b*0.05, $b*0.15);
        }
        if ($randPrice != null) {
            try{
                Db::startTrans();
                $currentPrice -= $randPrice;
                if($currentPrice<$lowestPrice){
                    $currentPrice = $lowestPrice;
                    $kanjiaModel->setAttr('is_lowest',1);
                }
                $kanjiaModel->setAttr('current_price',$currentPrice);
                $done = $kanjiaModel->allowField(true)->save();
                if(!$done){
                    throw new Exception();
                }
                $wxUser =AppWxUser::get($uid,null,true);
                $createdHelp = AdminKanjiaHelp::create(['tid'=>$kanjiaModel->tid,'kanjia_order_id'=>$kanJiaOrderId,'uid'=>$uid,'amount'=>$randPrice,'nickname'=>$wxUser->nickname,'head_img'=>$wxUser->head_img]);
                if($createdHelp){
                    Db::commit();
                    return ['done' => true, 'currentPrice' => $currentPrice,'randPrice'=>$randPrice];
                }else{
                    throw new Exception();
                }
            }catch (Exception $e){
                Db::rollback();
            }
        }
        return ['done' => false];
    }
}